<template>
  <!-- 维修套餐维护 -->
  <div>
    <!--条件筛选-->
    <TopFilter :list="topFilterList" :cols="3" labelWidth="85" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="repair-package-index"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
    >
      <!--列操作-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addEstimate">新增套餐</el-button>
        <AjaxButton size="small" type="primary" :click="repairPackageDistributeClick">下发</AjaxButton>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="exportClick">导出模板</el-button>
        <UploadFile style="margin: 0 10px;" :isOnlyButton="true" :limit="99" :actionUrl="`${server.DMSCLOUD_REPAIR}/repair/group/importRepairItemPackage`" @change="handleUploadChange"
          >Excel导入</UploadFile
        >
      </template>
    </FilterTable>

    <!--抽屉 -->
    <Drawer :visible.sync="estimate" :title="dialogTitle" :width="1100" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairPackageInfo :type="handleType" :info="formData" @close="closeEstimate" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { exportExcelFile } from '@/utils';
import SERVER from '@/api/server';
import { findGroupItem, repairPackageDistribute, getRepairTypes, getAllSeries, exportRepairItemPackage, importRepairItemPackage, getAllUser } from '@/api/repair/repairBusiness/repairPackage';
import repairPackageInfo from '@/pages/repair/repairBusiness/repairPackage_oem/repairPackageInfo';
import { getAppId } from '@/assets/js/auth';

// 延保订单查询
export default {
  name: 'repair-package-index',
  components: { repairPackageInfo },
  mixins: [dictionary],
  data() {
    return {
      server: SERVER,
      form: {
        fileList: []
      },
      fetchParams: { xhrAbort: false },
      dialogTitle: '',
      fetchApi: findGroupItem,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      tableData: [],
      selectFlag: false,
      topFilterList: this.createTopFilterList(),
      estimate: false
    };
  },
  created() {
    this.getRepairTypesFun();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getAllUser();
    this.getAllSeries(); // 不需要翻译code
    this.setFieldHidden(); // 设置字段禁用状态
  },
  methods: {
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode === 200) {
        let allUser = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(x => x.dataIndex === 'CREATED_BY').dictItems = allUser;
        this.columns.find(x => x.dataIndex === 'UPDATED_BY').dictItems = allUser;
      }
    },
    async getAllSeries() {
      let res = await getAllSeries();
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.topFilterList.find(x => x.fieldName === 'SERIES_CODE').itemList = series;
      }
    },

    // 导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e.length);
      if (e.length > 0) {
        this.$notify.success({ title: '提示信息', message: '导入成功!!!' });
        this.fetchParams = Object.assign({}, this.fetchParams);
        // this.loading = false;
      }
    },
    exportClick() {
      exportRepairItemPackage().then(res => {
        exportExcelFile(res.data, '维修套餐数据导入模板.xls');
      });
    },
    importClick() {},
    async repairPackageDistributeClick() {
      let packageCodes = [];
      this.tableData.forEach(x => {
        packageCodes.push(x.PACKAGE_CODE);
      });
      let res = await repairPackageDistribute(packageCodes);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '下发成功！！' });
      }
    },

    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.topFilterList.find(x => x.fieldName === 'REPAIR_TYPE_CODE').itemList = this.repairList;
      this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').dictItems = this.repairList;
      this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').filterItems = this.repairList;
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '套餐代码',
          fieldName: 'PACKAGE_CODE',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '套餐名称',
          fieldName: 'PACKAGE_TYPE_NAME',
          placeholder: '请输入...',
          maxlength: 100
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'REPAIR_TYPE_CODE',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'SERIES_CODE',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'ASSEMBLE_STATUS',
          placeholder: '请选择...',
          itemList: this.createDictList('1003')
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          hidden: false,
          itemList: [
            { text: '免费', value: 'M' },
            { text: '索赔', value: 'S' },
            { text: '自费', value: 'Z' }
          ]
          // rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        }

        // {
        //   type: 'SELECT',
        //   label: '数据来源',
        //   initialValue: 10451001,
        //   fieldName: 'DATA_SOURCES',
        //   placeholder: '请选择...',
        //   itemList: this.createDictList('1045')
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: '100',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '状态',
          dataIndex: 'ASSEMBLE_STATUS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.ASSEMBLE_STATUS, '1003')}</span>;
          }
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          hidden: false,
          sorter: true,
          dictItems: [
            { text: '免费', value: 'M' },
            { text: '索赔', value: 'S' },
            { text: '自费', value: 'Z' }
          ]
        },

        // {
        //   title: '数据来源',
        //   dataIndex: 'DATA_SOURCES',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1045'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.DATA_SOURCES, '1045')}</span>;
        //   }
        // },
        {
          title: '套餐代码',
          dataIndex: 'PACKAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '套餐名称',
          dataIndex: 'PACKAGE_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '车系',
          dataIndex: 'SERIES_CODE',
          hidden: true
        },
        {
          title: '车系',
          dataIndex: 'SERIES_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'CREATED_BY',
          width: 150,
          sorter: true,
          dictItems: []
        },
        {
          title: '创建时间',
          dataIndex: 'CREATED_AT',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        },
        {
          title: '修改人',
          dataIndex: 'UPDATED_BY',
          width: 150,
          sorter: true,
          dictItems: []
        },
        {
          title: '修改时间',
          dataIndex: 'UPDATED_AT',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        },
        {
          title: '下发时间',
          dataIndex: 'DOWN_AT',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        }
      ];
    },

    emitFun(val, type) {
      this.handleType = type;
      this.dialogTitle = `基本信息`;
      this.formData = val;
      this.estimate = true;
    },

    addEstimate() {
      // 新建
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      // 显示
      this.dialogTitle = `基本信息`;
      this.estimate = true;
    },
    selectData(val) {
      this.tableData = val;
      if (val.length == 0) {
        this.selectFlag = false;
      } else {
        this.selectFlag = true;
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    closeEstimate(val, type) {
      // 关闭
      this.estimate = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 设置字段禁用状态
    setFieldHidden() {
      if (getAppId() == 'beijing') {
        this.topFilterList.find(item => item.fieldName == 'CHARGE_PARTITION_CODE').hidden = true;
        this.columns.find(item => item.dataIndex == 'CHARGE_PARTITION_CODE').hidden = true;
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
